﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Silverlight.PreLoading;

namespace Silverlight.PreLoader
{
    public partial class MainPage : UserControl
    {
        private PreLoading.IPreLoadingQueue _queue;
        public MainPage()
        {
            InitializeComponent();
            _queue = new PreLoadingQueue();
            for(int i=1;i<100;i++)
            {
                string filename = string.Format("v{0}.mp4", i);
                _queue.Add(i.ToString(), new Silverlight.PreLoading.PreLoader("http://andrewmyhre.com/customassets/andrewmyhre/file/"+filename, "video"));
            }
            _queue.OnItemProgress += new EventHandler<PreLoadingProgressEventArgs>(_queue_OnItemProgress);
            _queue.OnItemPreLoaded += new EventHandler<LoadedEventArgs>(_queue_ItemLoaded);

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            _queue.ConnectionCount = 3;
            _queue.PreLoadAll();
        }

        void _queue_ItemLoaded(object sender, LoadedEventArgs e)
        {
            media.SetSource(e.Loaded.Stream);
        }

        void _queue_OnItemProgress(object sender, PreLoadingProgressEventArgs e)
        {
            //double eachProgress = 100 / (double)_initialCount;
            //double soFar = eachProgress * _downloaded + (eachProgress * e.Progress);
            message.Text = string.Format("Downloading video {0} of {1} ({2:#.#})%",
                _queue.CompletedCount + _queue.DownloadingCount, 
                _queue.CompletedCount+_queue.DownloadingCount+_queue.Count, 
                _queue.TotalProgress*100);
            progressBar.Value = _queue.TotalProgress * 100;
        }
    }
}
